package da.metricscraft.tools;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;

import com.ubempire.map.MetaPopulator;

import da.metricscraft.MetricsCraft;

public class MetricsCraftGenerator extends ChunkGenerator {
	protected byte[] result;

	@Override
	public byte[] generate(World world, Random rand, int chunkx, int chunkz) {
		result = new byte[16 * 16 * 128];
		for (int x = 0; x < 16; x++) {
			for (int z = 0; z < 16; z++) {
				for (int y = 50; y >= 0; y--) {
					if (y <= 50) {
						set(x, y, z, Material.STONE);
					} else if (y < 2) {
						set(x, y, z, Material.BEDROCK);
					} else {
						set(x, y, z, Material.STATIONARY_WATER);
					}
				}
			}
		}

		@SuppressWarnings("unused")
		int cx2 = chunkx, cz2 = chunkz;

//		while (chunkx < -xbound) {
//			chunkx += 2 * xbound;
//		}
//		while (chunkz < -zbound) {
//			chunkz += 2 * zbound;
//		}
//		while (chunkx > xbound) {
//			chunkx -= 2 * xbound;
//		}
//		while (chunkz > zbound) {
//			chunkz -= 2 * zbound;
//		}

//		int startx = (chunkx + xbound) * 16;
//		int startz = (chunkz + zbound) * 16;

		for (int x = 0; x < 16; ++x) {
			for (int z = 0; z < 16; ++z) {
				int y = 50 + (int)(2*Math.random());
				if (y < 55) {
					set(x, y, z, Material.DIRT);
				} else {
					set(x, y, z, Material.GRASS);
				}
				int count = 0;
				for (y = y - 1; y >= 0; y--) {
					if (count < 2) {
						set(x, y, z, Material.DIRT);
						count++;
					} else {
						set(x, y, z, Material.STONE);
					}
				}
				set(x, 1, z, Material.BEDROCK);
			}
		}
		//MetricsCraft.log.info("[MetricsCraftGenerator][generate]Generating chunk");
		return result;
	}
	@Override
	public List<BlockPopulator> getDefaultPopulators(World world) {
		return Arrays.<BlockPopulator>asList(new MetaPopulator());
	}
	private void set(int x, int y, int z, Material mat) {
		result[(x * 16 + z) * 128 + y] = (byte) mat.getId();
	}
}
